#ifndef MSGMANAGER_H
#define MSGMANAGER_H

#include <Windows.h>
#include "host.h"
#include "buffer.h"

struct Cfg;
struct ConnectInfo;

class MsgManager
{
public:
	MsgManager( ULONG nicAddr, int portNum, Cfg* cfg = NULL );
	~MsgManager();

	bool GetStatus( void ){ return _status; }
	HostSub* GetLocalHost( void ){ return &_local; }
	void CloseSocket( void );
	bool IsAvailableTCP(){ return _tcpSock != INVALID_SOCKET; }

	bool Send( HostSub* hostSub, ULONG command, int value );
	bool Send( HostSub* hostSub, ULONG command, const char* message = NULL, const char* exMsg = NULL );
	bool Send( ULONG hostAddr, int portNum, ULONG command, const char* message = NULL,
		const char* exMsg = NULL );
	bool AsyncSelectRegister( HWND hWnd );
	bool Recv( MsgBuf* msg );
	bool ResolveMsg( RecvBuf* buf, MsgBuf* msg );
	ULONG MakePacketNum( void ){ return _packetNum++; }
	ULONG MakeMsg( char* udpMsg, int packetNum, ULONG command, const char* msg,
		const char* exMsg = NULL, int* packetLen = NULL );
	ULONG MakeMsg( char* udpMsg, ULONG command, const char* msg, const char* exMsg = NULL,
		int* packetLen = NULL )
	{
		return MakeMsg( udpMsg, MakePacketNum(), command, msg, exMsg, packetLen );
	}
	bool UdpSend( ULONG hostAddr, int portNum, const char* udpMsg );
	bool UdpSend( ULONG hostAddr, int portNUm, const char* udpMsg, int len );
	bool UdpRecv( RecvBuf* buf );

	bool Accept( HWND hWnd, ConnectInfo* info );
	bool Connect( HWND hWnd, ConnectInfo* info );
	bool AsyncSelectConnect( HWND hWnd, ConnectInfo* info );
	bool ConnectDone( HWND hWnd, ConnectInfo* info );

	static int LocalNewLineToUnix( const char* src, char* dest, int maxLen );
	static int UnixNewLineToLocal( const char* src, char* dest, int maxLen );

protected:
	bool WSockInit( bool recvFlag );
	void WSockTerm( void );
	bool WSockReset( void );

protected:
	SOCKET	_udpSock;
	SOCKET	_tcpSock;

	bool	_status;
	ULONG	_packetNum;
	Cfg*	_cfg;

	HWND	_hAsyncWnd;
	UINT	_asyncMsg;
	UINT	_asyncMode;
	HostSub _local;
};

#endif	// MSGMANAGER_H